<template>
    <div class="addModule">
        <div class="topNav">
            <el-divider class="topLine"><i class="lineIcon el-icon-document-copy"></i><span
                    class="lineTitle" id="optionModule">新建模块表</span></el-divider>
        </div>
        <div class="moduleSetNav">
        </div>
        <div class="addContent">
            <!--开启表单验证：:rules="rules" ref="moudle" 表单右侧验证符号 status-icon -->
            <el-form :model="module" status-icon :rules="rules" label-width="100px" ref="module"
                     :label-position="labelPosition" >

                <el-form-item label="模块名称" prop="name">
                    <el-input id="name" class="inputLine" v-model="module.name" ></el-input>
                </el-form-item>


                <el-form-item label="SEO标题" prop="seoTitle">
                    <el-input id="seoTitle" class="inputLine" v-model="module.seoTitle" ></el-input>
                </el-form-item>


                <el-form-item label="SEO关键字" prop="seoKeyword">
                    <el-tag class="keyTags" id="seoKeyword"
                            :key="tag"
                            v-for="tag in seoKeyword"
                            closable
                            :disable-transitions="false"
                            @close="handleClose(tag)">
                        {{tag}}
                    </el-tag>
                    <el-input
                            class="input-new-tag"
                            v-if="inputVisible"
                            v-model="seoKey"
                            ref="saveKeyInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm"
                            @blur="handleInputConfirm"
                    >
                    </el-input>
                    <el-button v-else class="keyTagsInput button-new-tag" size="small" @click="showInput">+ SEO关键字</el-button>
                </el-form-item>


                <el-form-item label="SEO描述" prop="seoDescription">
                    <el-input id="seoDescription" class="inputLine" type="textarea" :rows="2" v-model="module.seoDescription" ></el-input>
                </el-form-item>

                <el-form-item label="模块内容" prop="moduleContent">
                    <el-input id="content" v-model="module.moduleContent"></el-input>
                </el-form-item>

                <el-form-item label="模块图片" prop="picList">
                    <big-file :upload-tile="'上传图片'" :input-id="'upload-article-icon'"
                              :suffix-type="['jpg','jpeg','png','gif']"
                              :uniId="module.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_PUBLIC.key"
                              :after-upload="afterUpload"></big-file>
                </el-form-item>

                <el-row class="upload-file-list" v-if="files.length>0">
                    <el-col :span="20">
                        <div class="file-image" v-for="file in files" :key="file.index">
                            <el-image class="img-url"
                                      :src="file"
                                      :preview-src-list="files"
                            >
                            </el-image>
                            <div class="img-after">
                                <!--<span class="glyphicon glyphicon-trash"></span>
                                <p>刪除</p>-->
                                <el-button class="img-del" type="danger" icon="glyphicon glyphicon-trash"
                                           @click="removeImg(file)"></el-button>
                            </div>

                        </div>
                    </el-col>
                </el-row>

                <el-form-item label="模块封面" prop="picCover">
                    <big-file :upload-tile="'上传封面'" :input-id="'upload-cover-icon'"
                              :suffix-type="['jpg','jpeg','png','gif']"
                              :uniId="module.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_PUBLIC.key"
                              :after-upload="afterCoverUpload"></big-file>
                    <el-row class="upload-icon">
                        <el-col :span="12">
                            <img :src="module.picCover" class="img-responsive" />
                        </el-col>
                    </el-row>
                </el-form-item>

                <!--<el-form-item label="父ID" prop="parentId">
                    <el-input id="parentId" class="inputLine" v-model="module.parentId" ></el-input>
                </el-form-item>-->


                <el-form-item label="模块类型" prop="typeId">
                    <el-select id="typeId" class="inputLine" v-model="module.typeId" placeholder="请选择">
                        <el-option
                                v-for="item in moduleTypes"
                                :key="item.key"
                                :label="item.value"
                                :value="item.key"
                                :disabled="item.disabled">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="模块路径" prop="modulePath">
                    <el-input id="modulePath" class="inputLine" v-model="module.modulePath" ></el-input>
                </el-form-item>
                <el-form-item label="引用模板路径" prop="templatePath">
                    <el-input id="templatePath" class="inputLine" v-model="module.templatePath" ></el-input>
                </el-form-item>
                <el-form-item label="页内模板路径" prop="subTemplatePath">
                    <el-input id="subTemplatePath" class="inputLine" v-model="module.subTemplatePath" ></el-input>
                </el-form-item>
                <!--<el-form-item label="分类所属" prop="category">
                    <el-cascader class="categoryInput inputLine" ref="categoryInput"
                                 placeholder="输入内容搜索分类"
                                 v-model="categoryUniIds"
                                 :options="categorys"
                                 :props="{value:'uniId',label:'name',children:'children'}"
                                 filterable
                                 @change="categoryChange">
                    </el-cascader>
                </el-form-item>-->
                <!--<el-form-item label="时长" prop="videoTime">
                    <el-input id="videoTime" class="inputLine" v-model="module.videoTime" ></el-input>
                </el-form-item>-->
                <el-form-item label="手机图片列表" prop="miniPicList">
                    <big-file :upload-tile="'上传图片'" :input-id="'upload-module-mini-pic-list'"
                              :suffix-type="['jpg','jpeg','png','gif']"
                              :uniId="module.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_PUBLIC.key"
                              :after-upload="afterMiNiUpload"></big-file>
                </el-form-item>
                <el-row class="upload-file-list" v-if="filesMiNi.length>0">
                    <el-col :span="20">
                        <div class="file-image" v-for="file in filesMiNi" :key="file.index">
                            <el-image class="img-url"
                                      :src="file"
                                      :preview-src-list="filesMiNi"
                            >
                            </el-image>
                            <div class="img-after">
                                <!--<span class="glyphicon glyphicon-trash"></span>
                                <p>刪除</p>-->
                                <el-button class="img-del" type="danger" icon="glyphicon glyphicon-trash"
                                           @click="removeMiNiImg(file)"></el-button>
                            </div>

                        </div>
                    </el-col>
                </el-row>

                <el-form-item label="核心内容图标" prop="iconList">
                    <big-file :upload-tile="'上传图标'" :input-id="'upload-module-icon-list'"
                              :suffix-type="['jpg','jpeg','png','gif']"
                              :uniId="module.uniId" :use-type="SOURCE_USE_TYPE.SOURCE_PUBLIC.key"
                              :after-upload="afterIconUpload"></big-file>
                    <span class="coreSuggest">图标上传建议尺寸：50*50px</span>
                </el-form-item>
                <el-row class="upload-file-icon-list" v-if="filesIcon.length>0">
                    <el-col :span="20">
                        <div class="file-image" v-for="file in filesIcon" :key="file.index">
                            <el-image class="img-url"
                                      :src="file"
                                      :preview-src-list="filesIcon"
                            >
                            </el-image>
                            <div class="img-after">
                                <!--<span class="glyphicon glyphicon-trash"></span>
                                <p>刪除</p>-->
                                <el-button class="img-del" type="danger" icon="glyphicon glyphicon-trash"
                                           @click="removeIconImg(file)"></el-button>
                            </div>

                        </div>
                    </el-col>
                </el-row>

                <el-form-item label="核心模块描述" prop="coreDescDto">
                    <div class="coreList">
                        <el-popover class="coreDescPopover"
                                    placement="top-start"
                                    title="选择图标"
                                    trigger="hover"
                        >
                            <div class="coreIcon" v-for="(icon,index) in filesIcon" :key="index">
                                <img class="iconImg" :src="icon" @click="toggleCoreIcon(icon)"/>
                            </div>
                            <!--<span class="addCore el-icon-circle-plus" type="primary"></span>-->
                            <el-button slot="reference">
                                <img v-if="coreDescDto.icon" class="iconImg" :src="coreDescDto.icon" alt="选择图标"/>
                                <span v-if="!coreDescDto.icon">选择图标</span>
                            </el-button>
                        </el-popover>

                        <el-input class="inputCoreTitle" v-model="coreDescDto.title" placeholder="模块标题"></el-input>
                        <el-input class="inputCoreDesc" :rows="2"
                                  type="textarea"
                                  placeholder="模块内容"
                                  maxlength="22"
                                  show-word-limit
                                  v-model="coreDescDto.desc">
                        </el-input>
                        <el-button class="addCore" type="primary" @click="addCore">添加<i
                                class="el-icon-plus el-icon--right"></i></el-button>
                    </div>

                </el-form-item>
                <el-row>
                    <el-table v-if="coreDesc.length>0"
                              :data="coreDesc"
                              style="width: 100%"
                              max-height="250"
                              class="previous-row"
                              ref="multipleTable">
                        <el-table-column class="coreIconItem"
                                         fixed
                                         prop="icon"
                                         label="图标"
                                         width="80" :show-overflow-tooltip="true">
                            <template slot-scope="scope">
                                <!--<el-avatar v-if="!employee.icon" src="../../imgs/logo300-1.png"></el-avatar>-->
                                <el-avatar class="coreIcon" :src="scope.row.icon"></el-avatar>
                            </template>
                        </el-table-column>
                        <el-table-column
                                fixed
                                prop="title"
                                label="标题"
                                width="100" :show-overflow-tooltip="true">
                        </el-table-column>
                        <el-table-column
                                prop="desc"
                                label="内容"
                                :show-overflow-tooltip="true">
                        </el-table-column>

                        <el-table-column
                                fixed="right"
                                label="操作"
                                width="200">
                            <template slot-scope="scope">
                                <el-button class="editCore"
                                           @click="editCore(scope.row)"
                                           type="primary"
                                >
                                    编辑
                                </el-button>
                                <el-button class="delCore"
                                           @click="delCore(scope.row)"
                                           type="danger"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-row>
                <el-form-item label="显示1 " prop="isShow">
                    <el-switch id="isShow" class="inputLine"
                               v-model="module.isShow"
                               active-color="#13ce66"
                               inactive-color="#ff4949"
                               :active-value="1"
                               :inactive-value="0"
                    >
                    </el-switch>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input id="sort" class="inputLine" v-model="module.sort" ></el-input>
                </el-form-item>
                <el-form-item>
                    <!--这里save(formName)方法保存，ref别名的module-->
                    <el-button id="submitBtn" type="primary" @click="save('module')">立即创建</el-button>
                    <el-button @click="resetForm('module')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="editSingle">
            <el-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" class="dialogDef">
                <div slot="title" class="header-title">
                    <div style="padding:15px 20px;">{{this.dialogTitle}}</div>
                </div>
                <!--绑定校验规则，必须这里:model绑定模块，ref做别名，:rules指定规则-->
                <el-form v-model="coreDescDto" :model="coreDescDto" ref="coreDescDto" :rules="rules" status-icon>
                    <el-form-item :label="labelName" :label-width="formLabelWidth" prop="name">
                        <el-avatar class="inputWidth coreIcon" :src="coreDescDto.icon"></el-avatar>
                    </el-form-item>
                    <el-form-item :label="labelContent" :label-width="formLabelWidth" prop="tag">
                        <el-input class="inputWidth" v-model="coreDescDto.title"></el-input>
                    </el-form-item>
                    <el-form-item :label="labelLargeContent" :label-width="formLabelWidth" prop="content">
                        <el-input class="inputContent" :rows="2"
                                  type="textarea"
                                  maxlength="22"
                                  show-word-limit
                                  placeholder="模块内容"
                                  v-model="coreDescDto.desc">
                        </el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveCore(coreDescDto)">保 存</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import BigFile from "../../../components/BigFile";
    export default {
        name: "AddModule",
        components:{BigFile},
        props:{
            list:{
                type:Function,
                default:null
            },
        },
        data() {
            let nameValidate=(rule,value,callback)=>{
                //regular正则：数字、任意大小写字母，不可以有下划线
                //中文字符：[\u4e00-\u9fa5]
                //任意字母数字：[a-zA-Z0-9]
                //以...开头：^
                //以...结尾：$
                //中文字符：\u4e00-\u9fa5
                //字符限制3位以外正确：{0,3}$
                //js包含 rmValue.indexOf("!")
                let regBlank = /^[a-zA-Z0-9\s]{0,3}$/;
                let removeReg=/^\s*|\s{0,}$/g;

                let rmValue=value;
                if (value === '') {
                    callback(new Error('模块标题不能为空'));
                } else if(regBlank.test(rmValue)){
                    callback(new Error('必须由中文、字母、数字组成，可以有空格'));
                    let modulePath=document.getElementById("modulePath");
                    this.module.modulePath='';
                    regBlank.test(rmValue);
                } else {
                    var strApp=rmValue.replace(removeReg,"");
                    var blankApp=strApp.replace(/\s{1,}/g,"-");
                    let modulePath=document.getElementById("modulePath");
                    modulePath.value=blankApp;
                    //需要在显示后，继续定义modulePath
                    this.module.modulePath=blankApp;
                    callback();
                    regBlank.test(rmValue);
                }

            }
            let seoTitleValidate=(rule,value,callback)=>{
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g,'c').length;
                }
                if(value===''){
                    callback(new Error("SEO标题不能为空"));
                }else if(getLength(value)<2){
                    callback(new Error("SEO标题长度至少3位"));
                }else{
                    callback();
                }
            }
            let seoDescriptionValidate=(rule,value,callback)=>{
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g,'c').length;
                }
                if(value===''){
                    callback(new Error("SEO描述不能为空"));
                }else if(getLength(value)<2){
                    callback(new Error("SEO描述长度至少3位"));
                }else{
                    callback();
                }
            }
            let modulePathValidate=(rule,value,callback)=>{
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g,'c').length;
                }
                if(value===''){
                    callback(new Error("模块路径不能为空"));
                }else if(getLength(value)<2){
                    callback(new Error("模块路径长度至少3位"));
                }else{
                    callback();
                }
            }
            let templatePathValidate=(rule,value,callback)=>{
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g,'c').length;
                }
                if(value===''){
                    callback(new Error("引用模板路径不能为空"));
                }else if(getLength(value)<2){
                    callback(new Error("引用模板路径长度至少3位"));
                }else{
                    callback();
                }
            }
            let subTemplatePathValidate=(rule,value,callback)=>{
                function getLength(str) {
                    //如果为中文，替换为ccc，1个中文字符计算长度=1
                    return str.replace(/[^x00-xff]/g,'c').length;
                }
                if(value===''){
                    callback(new Error("引用页内模板路径不能为空"));
                }else if(getLength(value)<2){
                    callback(new Error("引用页内模板路径长度至少3位"));
                }else{
                    callback();
                }
            }

            return {
                message: '这里是更新模块表页面',
                module:{
                    uniId:'',
                    name:'',
                    seoTitle:'',
                    seoKeyword:'',
                    seoDescription:'',
                    moduleContent:'',
                    picList:'',
                    parentId:'',
                    typeId:'',
                    modulePath:'',
                    templatePath:'',
                    subTemplatePath:'',
                    isShow:'',
                    sort:'',
                    createTime:'',
                    updateTime:'',
                    iCreateTime:'',
                    iUpdateTime:'',
                },
                moduleName:'',
                labelPosition: 'left',

                rules: {
                    name:[
                        {validator:nameValidate,trigger:'blur'}
                    ],
                    seoTitle:[
                        {validator:seoTitleValidate,trigger:'blur'}
                    ],
                    seoDescription:[
                        {validator:seoDescriptionValidate,trigger:'blur'}
                    ],
                    /*modulePath:[
                        {validator:modulePathValidate,trigger:'blur'}
                    ],
                    templatePath:[
                        {validator:templatePathValidate,trigger:'blur'}
                    ],
                    subTemplatePath:[
                        {validator:subTemplatePathValidate,trigger:'blur'}
                    ],*/


                },
                //文件上传：封面上传，这里的地址，vue默认搜索public，不需要添加public：../../imgs/BG-WALL.png
                files: [],
                filesMiNi:[],//手机端图片
                filesIcon:[],//图标集合
                //核心内容对象
                coreDesc: [],
                coreDescDto: {},
                coreDto:{},
                showIcon: '',
                dialogFormVisible: false,
                dialogTitle: '',
                labelName: '',
                disabled: 'disabled',
                labelContent: '',
                labelLargeContent: '',
                formLabelWidth: '120px',
                /*seo关键字*/
                inputVisible: false,
                seoKey: '',
                seoKeyword: [],

                options:VIDEO_TYPE,
                charge:VIDEO_CHARGE,
                isShow:YES_OR_NO,
                level:LEVEL,
                status:STATUS,
                moduleTypes: MODULE_TYPE,
                //级联选择
                value: [],
                //分类
                categorys: [],
                category:[],
                categoryUniIds:[],
                //文件上传
                SOURCE_USE_TYPE:SOURCE_USE_TYPE,
            }
        },
        mounted() {
            if(this.$route.params.moduleSub!=null){
                this.module.parentId='';
                this.module=this.$route.params.moduleSub;
                /*判断seoKeyword，避免为空出现tag标签*/
                if(!Tool.isEmpty(this.module.seoKeyword.toString())){
                    this.seoKeyword=this.module.seoKeyword;
                }else {
                    this.seoKeyword=[];
                }
                if (!Tool.isEmpty(this.module.picList.toString())) {
                    for (let i = 0; i < this.module.picList.length; i++) {
                        this.files = this.module.picList;
                    }
                } else {
                    this.files = [];
                }
                if (!Tool.isEmpty(this.module.miniPicList.toString())) {
                    for (let i = 0; i < this.module.miniPicList.length; i++) {
                        this.filesMiNi = this.module.miniPicList;
                    }
                } else {
                    this.filesMiNi = [];
                }
                if (!Tool.isEmpty(this.module.iconList.toString())) {
                    for (let i = 0; i < this.module.iconList.length; i++) {
                        this.filesIcon = this.module.iconList;
                    }
                } else {
                    this.filesIcon = [];
                }
                if (!Tool.isEmpty(this.module.coreDescDtos.toString())) {
                    this.coreDesc = this.module.coreDescDtos;
                } else {
                    this.coreDesc = [];
                }

                let optionModule=document.getElementById("optionModule");
                let submitBtn=document.getElementById("submitBtn");
                optionModule.innerHTML='更新模块表';
                submitBtn.innerHTML="立即更新";
            }else{
                //获取session中的moduleId
                let moduleIds=SessionStorage.get(MODULE_ID) || {};
                if(moduleIds!=null){

                    this.module={};
                    this.module.parentId=moduleIds;
                }
            }

            //获取文件分片大小
            function getShardFile(shardIndex, shardSize,files){
                let _this = this;
                let file = files;
                let start = (shardIndex - 1) * shardSize; //分片起始大小
                let end = Math.min(file.size, start + shardSize);
                //从start→end截取当前的分片数据
                let shardFile = file.slice(start, end);
                return shardFile;
            }
            function upload(param,file){
                let shardTotal = param.shardTotal;
                let shardIndex = param.shardIndex;
                let shardSize = param.shardSize;
                let files=file;
                let shardFile = getShardFile(shardIndex, shardSize,files);
                let token = Tool.getEmpLogin().token;
                let fileReader = new FileReader();
                Progress.show(parseInt((shardIndex - 1) * 100 / shardTotal));
                //先加载fileReader，读取到e，再进行数据shardFile转换
                fileReader.onload = function (e) {
                    let base64 = e.target.result;
                    param.shard = base64;
                    $.ajax({
                        url: 'http://127.0.0.1:8899/source/admin/oss/append',//后台文件上传接口
                        type: 'POST',
                        data: JSON.stringify(param), //转json上传fileDto对象
                        dataType: "json",
                        headers: {
                            'token': token, //加入请求头token校验
                        },
                        processData: false,
                        contentType: "application/json;charset=UTF-8",
                        success: function (data) {
                            let resp = data.data;
                            Progress.show(parseInt(shardIndex * 100 / shardTotal));
                            //判断分片的shardIndex和shardTotal值，是否分片上传完毕
                            if (shardIndex < shardTotal) {
                                param.shardIndex = param.shardIndex + 1;
                                upload(param);
                            } else {
                                Progress.hide();
                                $('#content').summernote('insertImage', data.responseData.path, 'img');
                            }
                        }
                    });
                }
                //需要放在fileReader之后，生成shardFile
                fileReader.readAsDataURL(shardFile);
            }

            //1.初始化富文本
            $("#content").summernote({
                lang: 'zh-CN',
                focus: true,
                height: 300,
                //自定义工具栏
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'italic', 'underline', 'clear', 'strikethrough', 'superscript', 'subscript']],
                    ['fontname', ['fontname']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph', 'fontsize', 'height', 'hr']],
                    ['table', ['table']],
                    ['insert', ['link', 'picture', 'video']],//插入集合
                    ['view', ['codeview', 'help']]
                ],
                callbacks: {
                    //这里原生js暴露的方法名必须相同
                    onImageUpload: function (files) {
                        let _this = this;
                        let file = files[0];
                        let formData = new FormData();
                        formData.append('file', file);
                        let token = Tool.getEmpLogin().token;

                        /*************************************************************/
                        let shardKey16 = hex_md5(file.name + file.size + file.type); //md5:16进制处理file
                        let shardKey10 = parseInt(shardKey16, 16);//转换为10进制
                        //62进制(短key)：26个大写字母+26个小写字母+10个阿拉伯数字
                        let shardKey62 = Tool.md_10to64(shardKey10);

                        //file类型判断["jpg","jpeg","png","gif"]
                        let suffixType = ["jpg", "jpeg", "png", "gif"];
                        let fileName = file.name;
                        let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
                        let validateSuffix = false;
                        //循环后缀类型
                        for (let i = 0; i < suffixType.length; i++) {
                            if (suffixType[i].toLowerCase() === suffix) {
                                validateSuffix = true;
                                break;
                            }
                        }
                        if (!validateSuffix) {
                            toast.warning("文件格式不正确，只支持上传：" + suffixType.join(",") + "文件");
                            return;
                        }

                        //文件分片shard
                        let shardSize = 1024 * 1024; //每1MB为一个分片，
                        let startIndex = 1; //分片起始索引，1为第一个分片
                        let size = file.size;//文件大小
                        let shardTotal = Math.ceil(size / shardSize);//分片总数，向上取整1.1=2
                        let contentType = file.type;
                        /**
                         * 统一请求参数，使用formData传递，需要将file中的shardFile转为base64的字符串string
                         * fileReader加载时，接收参数e,转为base64 = e.target.result
                         * base64字符串：文件说明+","+base64码(文件内容)
                         * 在fileReader包裹后，需要_this=this;
                         */
                        let param = {
                            'size': size,
                            'shardIndex': startIndex,
                            'shardSize': shardSize,
                            'shardTotal': shardTotal,
                            'name': file.name,
                            'suffix': suffix,
                            'shardKey': shardKey62,
                            'contentType': contentType,
                            'moduleId': '',
                            'useType': 'T',
                        };
                        $.ajax({
                            url: 'http://127.0.0.1:8899/source/admin/check/file/' + param.shardKey,//后台文件上传接口
                            type: 'GET',
                            headers: {
                                'token': token,
                            },
                            success: function (data) {
                                let fileDto = data.responseData;
                                if (!fileDto) {
                                    param.shardIndex = 1;
                                    upload(param,file);

                                } else if (fileDto.shardIndex === fileDto.shardTotal) {
                                    toast.success("文件急速秒传成功！");
                                    $('#content').summernote('insertImage', data.responseData.path, 'img');
                                } else {
                                    param.shardIndex = fileDto.shardIndex + 1;
                                    upload(param,file);
                                }
                            }
                        });
                    },

                }
            })
            //2.获取当前module的富文本内容
            $("#content").summernote('code', this.module.moduleContent);

        },
        methods: {
            filterTree(data){
                for(let i=0;i<data.length;i++){
                    if(data[i].children.length<1){
                        data[i].children=undefined;
                    }else{
                        this.filterTree(data[i].children);
                    }
                }
                return data;
            },

            //1.新增模块表
            save(formName) {
                let _this=this;
                let responseMsg='';
                let content=$("#content").summernote('code');

                this.module.moduleContent = content;
                this.module.picList = this.files;
                this.module.miniPicList=this.filesMiNi;
                this.module.iconList=this.filesIcon;
                this.module.coreDescDtos=this.coreDesc;
                this.module.seoKeyword=this.seoKeyword;
                //前端校验
                this.$refs[formName].validate((valid) => {
                    if (valid) {

                        this.$axios.post(process.env.VUE_APP_SERVER+'/business/admin/module/saveMC',this.module)
                            .then((response)=>{
                                let resp=response.data;
                                responseMsg=response;

                                if(resp.success){
                                    this.module={};
                                    this.module.parentId='';
                                    this.$router.push("/business/module/sub");
                                    //引入全局变量toast提示
                                    toast.success("保存成功","bottom-end");
                                }else {
                                    this.$notify({
                                        title: '填写内容错误',
                                        message: resp.responseMsg,
                                        position:"top-right",
                                        type: 'warning'
                                    });
                                }
                            })
                    } else {
                        this.$notify({
                            title: '填写内容错误',
                            message: '请按照提示内容填写正确信息',
                            position:"top-right",
                            type: 'warning'
                        });
                        return false;
                    }
                });

            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            //SEO标签
            handleClose(tag) {
                this.seoKeyword.splice(this.seoKeyword.indexOf(tag), 1);
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveKeyInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let seoKey = this.seoKey;
                if (seoKey) {
                    this.seoKeyword.push(seoKey);
                }
                this.inputVisible = false;
                this.seoKey = '';
            },
            //级联选择器
            handleChange(value) {
            },
            //文件上传
            //接收文件上传组件传入的resp
            afterUpload(resp){
                if (resp.success) {
                    //this.module.picList=resp.responseData.path;
                    let moduleId = this.module.uniId;
                    let picPath = resp.responseData.path;
                    if (!Tool.isEmpty(moduleId)) {
                        this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/module/savePicList',
                            {
                                moduleId: moduleId,
                                picPath: picPath
                            })
                            .then((response) => {
                                let resp = response.data;
                                if (resp.success) {
                                    let pics = [];
                                    for (let i = 0; i < resp.responseData.length; i++) {
                                        pics.push(resp.responseData[i]);
                                    }
                                    this.files = pics;
                                    toast.success("保存成功", "bottom-end");
                                } else {
                                    this.$notify({
                                        title: '保存失败，请联系管理员',
                                        message: resp.responseMsg,
                                        position: "top-right",
                                        type: 'warning'
                                    });
                                }
                            })
                    } else {
                        this.files.push(picPath);
                    }
                }
            },
            afterCoverUpload(resp){
                if(resp.success){
                    this.module.picCover=resp.responseData.path;
                    //避免图片不回显，强制渲染
                    this.$forceUpdate();
                }
            },
            //删除图片
            removeImg(file) {
                let boxMessage=document.querySelectorAll(".el-message-box .el-message-box__content .el-message-box__container .el-message-box__message p");
                for(let i=0;i<boxMessage.length;i++){
                    boxMessage[i].style="word-wrap:break-word";
                }
                this.$confirm('确认删除 【' + file + '】文件？', '删除图片操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.files.splice(this.files.indexOf(file), 1);
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                }).catch(() => {
                    this.$message({
                        type:'info',
                        message:'取消删除'
                    });
                });

            },
            afterMiNiUpload(resp){
                if (resp.success) {
                    //this.module.picList=resp.responseData.path;
                    let moduleId = this.module.uniId;
                    let picPath = resp.responseData.path;
                    if (!Tool.isEmpty(moduleId)) {
                        this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/module/saveMiniPicList',
                            {
                                moduleId: moduleId,
                                picPath: picPath
                            })
                            .then((response) => {
                                let resp = response.data;
                                if (resp.success) {
                                    let pics = [];
                                    for (let i = 0; i < resp.responseData.length; i++) {
                                        pics.push(resp.responseData[i]);
                                    }
                                    this.filesMiNi = pics;
                                    toast.success("保存成功", "bottom-end");
                                } else {
                                    this.$notify({
                                        title: '保存失败，请联系管理员',
                                        message: resp.responseMsg,
                                        position: "top-right",
                                        type: 'warning'
                                    });
                                }
                            })
                    } else {
                        this.filesMiNi.push(picPath);
                    }
                }
            },
            removeMiNiImg(file) {
                let boxMessage = document.querySelectorAll(".el-message-box .el-message-box__content .el-message-box__container .el-message-box__message p");
                for (let i = 0; i < boxMessage.length; i++) {
                    boxMessage[i].style = "word-wrap:break-word";
                }
                this.$confirm('确认删除 【' + file + '】文件？', '删除图片操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.filesMiNi.splice(this.filesMiNi.indexOf(file), 1);
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消删除'
                    });
                });

            },
            afterIconUpload(resp){
                if (resp.success) {
                    //this.module.picList=resp.responseData.path;
                    let moduleId = this.module.uniId;
                    let picPath = resp.responseData.path;
                    if (!Tool.isEmpty(moduleId)) {
                        this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/module/saveIconList',
                            {
                                moduleId: moduleId,
                                picPath: picPath
                            })
                            .then((response) => {
                                let resp = response.data;
                                if (resp.success) {
                                    let pics = [];
                                    for (let i = 0; i < resp.responseData.length; i++) {
                                        pics.push(resp.responseData[i]);
                                    }
                                    this.filesIcon = pics;
                                    toast.success("保存成功", "bottom-end");
                                } else {
                                    this.$notify({
                                        title: '保存失败，请联系管理员',
                                        message: resp.responseMsg,
                                        position: "top-right",
                                        type: 'warning'
                                    });
                                }
                            })
                    } else {
                        this.filesIcon.push(picPath);
                    }
                }
            },
            removeIconImg(file) {
                let boxMessage = document.querySelectorAll(".el-message-box .el-message-box__content .el-message-box__container .el-message-box__message p");
                for (let i = 0; i < boxMessage.length; i++) {
                    boxMessage[i].style = "word-wrap:break-word";
                }
                this.$confirm('确认删除 【' + file + '】文件？', '删除图片操作', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.filesIcon.splice(this.filesIcon.indexOf(file), 1);
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消删除'
                    });
                });

            },
            //切换图标
            toggleCoreIcon(icon){
                this.showIcon=icon;
                this.coreDescDto.icon=this.showIcon;
            },
            //核心模块编辑，删除
            addCore() {
                this.coreDesc.push(this.coreDescDto);
                this.coreDescDto = {};
            },
            editCore(core) {

                if(Tool.isEmpty(this.module.coreDescDtos)) {
                    const h = this.$createElement;
                    this.$notify.error({
                        title: '请先保存模块',
                        message: h('i', {style: 'color: teal'}, '请先保存模块，避免数据丢失'),
                        position: 'bottom-right'
                    });
                }else{
                    this.dialogFormVisible = true;
                    this.coreDescDto = $.extend({}, core);
                    let coreOri=core;
                    this.coreDto=coreOri;
                    this.dialogTitle = "编辑核心模块";
                    this.labelName = "图标";
                    this.labelContent = "标题";
                    this.labelLargeContent = "内容";
                }

            },
            saveCore(coreDescDto) {
                for(let i=0;i<this.coreDesc.length;i++){
                    if(this.coreDesc[i]===this.coreDto){
                        this.coreDesc[i]=coreDescDto;
                        //需要刷新save请求
                    }
                }
                this.module.seoKeyword = this.seoKeyword;
                this.module.coreDescDtos=this.coreDesc;
                this.module.picList = this.files;

                this.module.iconList=this.filesIcon;
                this.$axios.post(process.env.VUE_APP_SERVER + '/business/admin/module/saveMC', this.module)
                    .then((response) => {
                        let resp = response.data;
                        if (resp.success) {
                            let pics = [];
                            for (let i = 0; i < resp.responseData.iconList.length; i++) {
                                pics.push(resp.responseData.iconList[i]);
                            }
                            this.files=resp.responseData.picList;
                            this.filesIcon = pics;
                            this.coreDesc=resp.responseData.coreDescDtos;
                            toast.success("保存成功", "bottom-end");
                        } else {
                            this.$notify({
                                title: '保存失败，请联系管理员',
                                message: resp.responseMsg,
                                position: "top-right",
                                type: 'warning'
                            });
                        }
                    })

                this.dialogFormVisible = false;
                this.coreDescDto = {};

            },
            delCore(core) {
                this.coreDesc.splice(this.coreDesc.indexOf(core), 1);
            }
        },
    }
</script>

<style scoped>
    /*顶部line样式*/
    .topNav {

    }

    /deep/ .el-divider__text {
        background-color: #1d7dd6;
        padding: 8px 20px;
    }

    .topLine {
        background-color: #1d7dd6;
    }

    .lineIcon {
        font-size: 22px;
        color: #ffffff;
        position: relative;
        margin-right: 5px;
    }

    .lineTitle {
        position: relative;
        font-size: 16px;
        color: #ffffff;
    }

    /*模块表设置导航*/
    .moduleSetNav {
        max-width: 400px;
        margin: 5px auto;

    }

    .moduleSetNavTile {
        cursor: pointer;
    }

    /*内容区位置*/
    .addContent {
        margin-left: 5%;
        margin-top: 35px;
        margin-right: 5%;
    }

    /deep/ .el-form-item {
        margin-bottom: 5px;
    }

    /*输入行控制*/
    .inputLine {
        max-width: 350px;
        float: left;
    }

    /*关键字标签*/
    .el-tag + .el-tag {
        margin-left: 10px;
    }

    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }

    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }

    .titleLeft {
        float: left;
    }

    /*SEO描述*/
    .textAreaWidth {
        max-width: 400px;
        float: left;
    }

    /*图片上传：取消upload打开的input默认按钮*/
    /deep/ input[type=file] {
        display: block;
        margin-left: -950px;
    }

    /*错误提示*/
    #moduleTitle{
        float: left;
    }
    /deep/ .el-form-item__error{
        float: left;
        position: relative;
        line-height: 30px;
        margin-left: 10px;
    }
    /*提示框的字符颜色*/
    /deep/ .el-input__prefix, .el-input__suffix{
        color: #44cd3f ;
        font-size: 18px;
    }
    /deep/ .el-input__icon{
        color: #44cd3f ;
        font-size: 18px;
    }
    /*是否显示*/
    /deep/ .el-switch{
        line-height: 40px;
    }

    /*头像上传：如果没有可删除，picList*/
    .avatar-uploader{
        float: left;
    }
    .avatar-uploader  {
        border: 1px dashed #a8a2a2;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;
        text-align: center;
    }
    .avatar-uploader:hover {
        border-color: #409EFF;
    }
    .avatar-uploader:hover .avatar-uploader-icon{
        color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    /*关键字*/
    .keyTags{
        float: left;
        margin-right: 8px;
    }
    .keyTagsInput{
        float: left;
    }
    .input-new-tag{
        max-width: 230px;
        float: left;
    }
    /*封面上传*/
    /*/deep/ [data-v-64e0af8c] input[type=file]{
        display: block;
    }*/
    .upload-icon{
        margin-top: -50px;
        margin-bottom: 10px;
    }
    .upload-icon img{
        padding: 5px;
        border: 1px solid #cccccc;
    }
    /*文件列表*/

    .upload-file-list {
        margin-bottom: 10px;
        margin-top: -40px;
        margin-left: 13%;
    }

    .upload-file-list .el-image {
        width: 150px;
        float: left;
        padding: 5px;
        border: 1px solid #cccccc;
        margin-right: 5px;
    }
    .upload-file-list .file-image .img-url {
        position: relative;
    }

    /*.upload-file-list .file-image .img-url:hover:after{
        position: absolute;
        content: "删除 X";
        width: 50px;
        height: 20px;
        bottom: 5px;
        right: 5px;
        background-color: #409EFF;
        color: white;
        !*点击*!
        pointer-events: auto;
    }*/
    .upload-file-list .file-image .img-after {
        position: relative;
        float: left;
        margin-top: 56px;
        margin-left: -37px;
        color: white;
    }
    .upload-file-list .file-image .img-after .img-del {
        padding: 5px;
        border-radius: 0;
        background-color: #e92322;
        border: 1px solid #ffffff;
    }
    .upload-file-list .file-image .img-after .img-del:hover {
        background-color: #f6504f;
    }
    /*删除确认框：自动换行 word-wrap:break-word*/
    /*/deep/ .el-message-box .el-message-box__content .el-message-box__container .el-message-box__message p{
        word-wrap:break-word
    }*/

    /*图标列表*/
    .upload-file-icon-list {
        margin-bottom: 10px;
        margin-top: -40px;
        margin-left: 13%;
    }

    .upload-file-icon-list .el-image {
        width: 50px;
        float: left;
        padding: 5px;
        border: 1px solid #2a92ee;
        border-radius: 5px;
        margin-right: 5px;
    }

    .upload-file-icon-list .file-image .img-url {
        position: relative;
    }

    /*.upload-file-icon-list .file-image .img-url:hover:after{
        position: absolute;
        content: "删除 X";
        width: 50px;
        height: 20px;
        bottom: 5px;
        right: 5px;
        background-color: #409EFF;
        color: white;
        !*点击*!
        pointer-events: auto;
    }*/
    .upload-file-icon-list .file-image .img-after {
        position: relative;
        float: left;
        margin-top: 25px;
        margin-left: -20px;
        color: white;
    }

    .upload-file-icon-list .file-image .img-after .img-del {
        padding: 5px;
        border-radius: 15px;
        font-size: 10px;
        background-color: #e92322;
        border: 3px solid #ffffff;
        margin-right: 8px;
    }

    .upload-file-icon-list .file-image .img-after .img-del:hover {
        background-color: #f6504f;
    }

    /*删除确认框：自动换行 word-wrap:break-word*/
    /*封面上传*/
    .upload-icon{
        margin-top: -50px;
        margin-bottom: 10px;
    }
    .upload-icon img{
        padding: 5px;
        border: 1px solid #cccccc;
    }
    /*核心内容控件*/
    .coreDescPopover{
        float: left;
        margin-bottom: 10px;
        position: relative;
    }
    .coreDescPopover .el-button{
        padding: 5px 10px;
        line-height: 30px;
    }
    .coreIcon{
        border: 1px solid #2a92ee;
        border-radius: 5px;
        float: left;
        margin-right: 5px;
        margin-bottom: 10px;
    }
    .coreIcon .iconImg{
        width: 30px;
    }
    .inputCoreTitle{
        max-width: 350px;
        float: left;
        height: 40px;
        line-height: 40px;
        margin-left: 10px;
        margin-bottom: 10px;
    }
    .inputCoreDesc{
        max-width: 350px;
        float: left;
        margin-left: 10px;
    }
    .addCore{
        padding: 2px;
        font-size: 26px;
        color: #2a92ee;
        top: 0;
        margin-left: 20px;
    }

    /*table样式*/
    .previous-row {
        background: #f0f9eb;
        margin-left: 2%;
        max-width: 96%;

    }

    .coreIcon {
        background: #ffffff;
    }

    .optionList {
        text-align: center;
    }

    /deep/ .el-table td, .el-table th {
        padding: 5px 0;
        text-align: center;
    }

    /deep/ .el-table .cell {
        padding-right: 2px;
        line-height: 20px;
        text-align: center;

    }

    /deep/ .el-table .cell, .el-table--border td:first-child .cell, .el-table--border th:first-child .cell {
        padding-left: 5px;
    }

    .editCore{
        float: left;
    }
    .delCore{

    }
    /*模态框*/
    .header-title {
        background: #2589e7;
        color: white;
        font-size: 20px;
    }

    /deep/ .el-dialog__header {
        padding: 0;
    }

    /deep/ .el-dialog--center .el-dialog__body {
        background: #d2d3d04d;
    }

    /deep/ .el-dialog__headerbtn .el-dialog__close {
        color: white;
        font-size: 24px;
    }

    /deep/ .el-form-item__label {
        text-align: center;
        padding: 0;
    }

    /deep/ .el-dialog__body {
        padding: 20px 10px;
    }

    /deep/ .el-form-item {
        margin-bottom: 5px;
    }

    .inputWidth {
        max-width: 500px;
        float: left;
    }

    .inputContent {

    }
    /*添加核心模块*/
    .addCore {
        padding: 18px 20px;
        font-size: 16px;
        float: left;
        top: 0;
        margin-left: 5px;
        color: white;
    }
    .coreSuggest{
        position: absolute;
        display: block;
        top: 0;
        left: 100px;
        color: #2a92ee;
    }

</style>